import React, { useState, useRef, useEffect, useCallback, CSSProperties } from 'react';
import './index.scss';
import classNames from 'classnames';
import { Image, Skeleton, Toast } from 'antd-mobile';
import { bem, centsToYuan, isEmpty, useDebounceFn } from '@/utils';
import { GoodsDetailContextProps, GoodsBuyType } from './context';
import BuyArea from './BuyArea';
import GoodsOperator from './GoodsOperator';
import SealSwiper from '@/components/swiper';
import GdComment from './Comment';
import { useNavigate, useParams } from 'react-router-dom';
import { getDetail } from '@/api/product';
import { GoodsInfoType } from '@/components/sku/typing';
import Loadding from '@/components/loadding';

const defaultProps = {
  sku: {},
  unit: '个',
  bannerHeight: 375,
  navMore: [
    {
      title: '首页',
      jumpTo: '/',
    }
  ],
  convertData: (data: any): GoodsInfoType => {
    // Correctly map and return the expected structure
    const { subImages, productName, salePrice, mainImage } = data.productInfo;
    const sku = data.skuInfo || {};

    const { skuList, skuSpecs } = sku;
    const newSkuList = skuList.map((skuItem: any) => {
      return {
        skuId: skuItem.skuId,
        skuName: skuItem.skuName,
        skuPrice: centsToYuan(skuItem.skuPrice),
        stock: skuItem.availableStockNum,
        isMain: skuItem.isMain,
        aps: skuItem.aps || '',
      }
    });

    const descImages = subImages.split(',');
    return {
      goodsName: productName,
      goodsImgs: [mainImage],
      goodsDesc: descImages,
      mainImage,
      goodsPrice: salePrice,
      sku: {
        skuList: newSkuList,
        skuSpecs,
      },
    } as GoodsInfoType;
  },
}

const GoodsDetail: React.FC<GoodsDetailContextProps> = (props) => {
  const {
    sku,
    unit,
    bannerHeight,
    navMore,
    convertData,
    ...rest
  } = {
    ...defaultProps,
    ...props,
  };
  const b = bem('gd');

  const navigate = useNavigate();
  const goodsId = useParams().id;

  const [isLoading, setIsLoading] = useState(false);


  const [goodsInfo, setGoodsInfo] = useState<GoodsInfoType>({} as GoodsInfoType);



  console.log('GoodsDetail', goodsId);

  const fetchGoodsDetail = useCallback(async () => {
    if (isEmpty(goodsId)) {
      return;
    }
    if (isLoading) {
      return;
    }
    setIsLoading(true);
    return await getDetail({ productId: goodsId }).then((res) => {
      console.log("res", res);
      const goodsInfo = convertData(res.data);

      console.log('goodsInfo', goodsInfo);
      setGoodsInfo(goodsInfo);

      setIsLoading(false);
    });
  }, [])

  const debouncedFetchGoodsDetail = useDebounceFn(fetchGoodsDetail, 500);

  useEffect(() => {
    setIsLoading(true);
    debouncedFetchGoodsDetail.run();
  }, []);

  const handlerBuy = (value: GoodsBuyType) => {
    console.log("value", value);
    if (isEmpty(value)) {
      Toast.show('请选择数据');
      return;
    }
    navigate('/order/confirm')
  };

  const handlerAddCart = (value: GoodsBuyType) => {
    console.log("value", value);
    if (isEmpty(value)) {
      Toast.show('请选择数据');
      return;
    }
    navigate('/shoppingcart')
  };


  const getNavMoreList = () => {
    return (
      <ul className='seal-gd__nav-more'>
        {navMore.map((item, index) => (
          <li className='seal-gd__nav-more__item' key={index}>
            <a href={item?.jumpTo}>{item?.title}</a>
          </li>
        ))}
      </ul>
    );
  };





  // 显示加载中
  if (isLoading) {
    return (
      <div className={b()}>
        <Image height={bannerHeight} src='' />
        <Skeleton.Title />
        <Skeleton.Paragraph />
        <div className={b('loading')}>
          <Loadding visible={isLoading} />
        </div>
        <Skeleton.Title />
        <Skeleton.Paragraph />
      </div>
    )
  }

  return (

    <div className={classNames('box', b())}>
      <div className={b('head')} ></div>

      <div className={b('body')}>
        <SealSwiper
          mousewheel={true}
          offset={90}
          navTabShow
          scrollNavShow
          navMoreContent={getNavMoreList()}
        >
          <SealSwiper.Item key={1} title='商品' navShow={true}>
            {
              goodsInfo && (
                <BuyArea
                  goodsInfo={goodsInfo}
                  handlerBuy={handlerBuy}
                />
              )
            }
          </SealSwiper.Item>
          <SealSwiper.Item key={2} title='评价' navShow={true}>
            <div className={b('h')}></div>
            <GdComment />
          </SealSwiper.Item>
          <SealSwiper.Item key={3} title='详情' navShow={true}>
            <div className={b('h')}></div>
            <div className={b('desc')}>
              <div className={b('desc__title')}>
                商品详情
              </div>
              <div className={b('desc__content')}>
                {
                  goodsInfo.goodsDesc?.map((item, i) => (
                    <Image key={i} src={item} />
                  ))
                }
              </div>
            </div>
          </SealSwiper.Item>
        </SealSwiper>

        <Loadding type='noMore' visible={true} />
      </div>

      <div className='seal-footer seal-bottom-fixed'>
        <GoodsOperator
          onHandlerBuy={handlerBuy}
          onHandlerCart={handlerAddCart}
        />
      </div>
    </div>

  )
}

export default GoodsDetail;